<!--
**********************************************************
* @Author: 张小平
* @Date:   2024-05-01
* @Email:  qqshuqian@163.com
* @Last modified: 最后修改日期
* @Description: 文件描述
**********************************************************
-->
<template>
  <el-row style="font-size: 10px;">
    <el-col :span="17">

      <div class="h-edit-head-content-title edit-div" :contenteditable="canEdit" v-text="content" ref="myeditor"
           @input="changeText"
           @focus="isLocked = true"
           @blur="isLocked = false"
           @click="changeText1"
      >
      </div>
    </el-col>
    <el-col :span="3" style="margin-left: 10px;margin-right: 10px">
      <div class="file-upload-design"   contenteditable="false" v-if="canEdit"  >
        <div class="file-upload-design-icon" @click="dialog_show($event)" name="desgin" >
          <div class="file-upload-design-txt">上传</div>
          <input type="file" name="fileToUpload" style="display:none;" accept="image/*" @change='changeimage($event)'>
        </div>
      </div>

      <div v-if="canScore" style="margin-bottom: 5px">
        得分：<el-input maxlength="3" oninput="value=value.replace(/[^0-9]/g,'');"   v-model="stuScore"  ></el-input>
        <br>
      </div>
      <div v-if="!canEdit">
        <el-tooltip class="item" effect="dark" :content="titlecontent" placement="top-start">
          <el-button >答案</el-button>
        </el-tooltip>
      </div>
    </el-col>
  </el-row>
</template>

<script>
import website  from '@/framework-core/config/website';
import axios from 'axios'

export default {
  name: 'editor',
  props: {
    value: {
      type: String,
      required: true
    },
    title: {
      type: String,
      required: true
    },
    canEdit: {
      type: Boolean,
      required: false
    },
    canScore: {
      type: Boolean,
      required: false
    }
  },
  model: {
    prop: 'value',
    event: 'input',
  },
  data() {
    return {
      content: this.value, //编辑器内容
      titlecontent:this.title,
      stuScore:undefined,
      isLocked: false,
      selection: null,
      range: null,
      textNode: null,
      rangeStartOffset: null
    }
  },
  mounted(){
    //模板参数传参
    const _this = this
    window.previewBigImg = function (e) {
      _this.showImgBig(e);
    }
  },
  methods: {
    dialog_show (e) {
      this.upLoad();
    },
    // 请求-上传附件
    upLoad() {
      const _this = this;
      const fileType = ['png', 'jpg', 'jpeg']
      const inputFile = document.createElement("input")
      inputFile.type = "file"
      inputFile.style.display = "none"
      document.body.appendChild(inputFile)
      inputFile.click()
      inputFile.addEventListener("change", function () {
        const file = inputFile.files[0];
        var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
        if (!fileType.includes(testmsg)) {
          _this.$message.warning("上传的文件格式只能是'png','jpg','jpeg'");
          document.body.removeChild(inputFile);
          return false;
        }
        const config = {};
        config.headers = {'Content-Type': "multipart/form-data"};
        const formData = new FormData();
        formData.append("file", file);
        axios.post(website.baseUrl + "/api/sys/file/upload", formData, config).then((res) => {
          if (res.data.state == 200) {
            _this.$refs.myeditor.focus();
            _this.$refs.myeditor.selectionEnd = 0;

            _this.getMySelection();
            const parseDom = _this.parseDom(
                '<img class="edit-div-img" onclick="previewBigImg(\''+res.data.data.data.url+'\')"  style="min-width: 40px;height: 40px" src="' + res.data.data.data.url + '"/>'
            )
            // 在光标处插入dom
            _this.range.insertNode(parseDom)
            // 光标开始和光标结束重叠
            _this.range.collapse(true)
            _this.$message.success("上传成功")
            this.$emit('input', this.$refs.myeditor.innerHTML);
          } else {
            _this.$message.success("上传失败")

          }
        });
      })
    },
    showImgBig:function(e) {
      debugger
      let datas = [];
      let  index2=0;
      datas.push({ thumbUrl: e, url:e })
      this.$ImagePreview(datas, index2, {
        closeOnClickModal: true,
        click: (data, index2) => {
          //this.$message.success('点击事件' + index2)
        },
        beforeClose: () => {
          // this.$message.success('关闭回调')
        }
      });
    },
    getMySelection(){
      this.selection = getSelection();
      // 光标对象
      this.range = this.selection.getRangeAt(0)
      // 获取光标对象的范围界定对象
      this.textNode = this.range.startContainer
      // 获取光标位置
      this.rangeStartOffset = this.range.startOffset;
    },
    parseDom(arg) {
      var objE = document.createElement("div");
      objE.innerHTML = arg;
      return objE.childNodes[0];
    },
    changeText1(){
      if(!this.selection){
        this.getMySelection();
      }
    },
    changeText(){
      // let props = defineProps(['modelValue'])
      // let emit = defineEmits(['update:modelValue'])
      // emit('update:modelValue',"子改变值")
      this.$emit('input', this.$refs.myeditor.innerHTML);
      // this.content = this.$refs.myeditor.innerHTML;
    }
  }
  // , watch: {
  //   'value'(){
  //     if (!this.isLocked || !this.content) {
  //       this.content = this.value;
  //       //console.log(this.content);
  //     }
  //   }
  // }
}
</script>

<style scoped>



.edit-div {
  width: 100%;
  height: 100%;
  overflow: auto;
  word-break: break-all;
  outline: none;
  user-select: text;
  white-space: pre-wrap;
  text-align: left;
  border: 1px solid #d9d9d9;
}

.edit-div img{
  min-width: 40px;
  height: 40px;
}

.edit-div[contenteditable=true] {
  user-modify: read-write-plaintext-only;
  border: 1px solid #d9d9d9;
}
.edit-div[contenteditable=true]:empty:before {
  content: attr(placeholder);
  display: block;
  color: #ccc;
}


.file-upload-design{

  position: relative;
  overflow: hidden;
  background-color: #EBEBEB ;
  display: inline-block;
}
.file-upload-design-icon{
  width: 24px;
  height: 24px;
  background-image: url("/img/logo.png");
  background-size: 100% 100%;

}
.file-upload-design-icon:hover{
  cursor: pointer;
}
.file-upload-design-txt{
  margin-top: 9px;
  height: 12px;
  font-size: 10px;
  text-align: center;
  color: #AAAAAA;
}

@media ( max-width: 992px) {
  .el-col-20 {
    max-width: 80%;
    flex: 0 0 83.3333333333%;
  }
  .el-col-3 {
    max-width: 10%;
    flex: 0 0 12.5%;
  }
}



</style>
